package com.yzt.dynamicmodule.fragment

import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.yzt.dynamicmodule.R
import com.yzt.dynamicmodule.adapter.IndexDiscoverAdapter
import com.yzt.dynamicmodule.dialog.AddressGoOnDialog
import com.yzt.dynamicmodule.dialog.DynamicCommentDialog
import com.yzt.dynamicmodule.dialog.DynamicDetailDialog
import com.yzt.dynamicmodule.dialog.IndexShareDialog
import com.yzt.dynamicmodule.modle.DiscoverViewModel
import com.yzt.dynamicmodule.viewpagerlayoutmanager.OnViewPagerListener
import com.yzt.dynamicmodule.viewpagerlayoutmanager.ViewPagerLayoutManager
import com.yzt.p_base.utils.ToastUtil
import com.yzt.plugin_network.response.HttpResponse
import com.yzt.zhuju.arouter.RouterDynamic
import com.yzt.zhuju.arouter.RouterUser
import com.yzt.zhuju.base.BaseApplication
import com.yzt.zhuju.base.BaseFragment
import com.yzt.zhuju.dialog.BaseDialog
import com.yzt.zhuju.event.main.IndexLocalEvent
import com.yzt.zhuju.event.main.IndexVideoEvent
import com.yzt.zhuju.network.AresSubscriber
import com.yzt.zhuju.network.biz.BizLayer
import com.yzt.zhuju.network.entity.home.IndexDataBean
import com.yzt.zhuju.network.entity.user.FollowUserStatusRequest
import com.yzt.zhuju.utils.ViewUtil
import com.yzt.zhuju.utils.map.BdLocationUtil
import com.yzt.zhuju.widget.refreshHeader.WaterDropHeader
import xyz.doikki.videocontroller.TikTokController
import xyz.doikki.videocontroller.component.ErrorView
import xyz.doikki.videocontroller.component.VideoPrepareView
import xyz.doikki.videocontroller.component.VideoVodControlView
import xyz.doikki.videocontroller.util.Utils
import xyz.doikki.videoplayer.player.BaseVideoView
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.player.VideoViewManager

/**
 * author : bob
 * date   : 2022/11/15
 * desc   : 首页发现
 */
class IndexDiscoverFragment : BaseFragment(), OnRefreshListener {

    // 当前播放的位置
    private var mCurPos = -1

    // 上次播放的位置，用于页面切回来之后恢复播放
    private var mLastPos = mCurPos

    private var mRefreshLayout: RefreshLayout? = null
    private var extraType = 1
    private var cityCode: String? = null
    private var lat: String? = null
    private var lng: String? = null

    private var mVideoView: VideoView? = null
    private var mController: TikTokController? = null
    private var mErrorView: ErrorView? = null

    companion object {
        fun getInstance(type: Int): IndexDiscoverFragment {
            val args = Bundle()
            args.putInt("extra_type", type)
            val fragment = IndexDiscoverFragment()
            fragment.arguments = args
            return fragment
        }

        fun getInstance(type: Int, userId: String, dynamicId: String): IndexDiscoverFragment {
            val args = Bundle()
            args.putInt("extra_type", type)
            args.putString("extra_user_id", userId)
            args.putString("extra_dynamic_id", dynamicId)
            val fragment = IndexDiscoverFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val discoverAdapter: IndexDiscoverAdapter by lazy {
        IndexDiscoverAdapter()
    }

    private val findViewModel: DiscoverViewModel by lazy {
        ViewModelProvider(this)[DiscoverViewModel::class.java]
    }

    private val viewPagerLayoutManager: ViewPagerLayoutManager by lazy {
        ViewPagerLayoutManager(mActivity)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_index_discover
    }

    var extraUserId: String? = null
    var extraDynamicId: String? = null

    override fun installViews() {
        extraType = arguments?.getInt("extra_type", 1)!!
        extraUserId = arguments?.getString("extra_user_id")
        extraDynamicId = arguments?.getString("extra_dynamic_id")
        initRecyclerView()
        addListener()
        initVideoView()
        observer()
        if (extraType == -1) {
            findViewModel.getIndexDiscover(
                extraUserId, extraDynamicId, mCurrentPage, PAGE_SIZE
            )
        } else {
            findViewModel.getIndexDiscover(
                extraType,
                BdLocationUtil.getInstance().cityCode.toString(),
                BdLocationUtil.getInstance().lat,
                BdLocationUtil.getInstance().lng,
                mCurrentPage,
                PAGE_SIZE
            )
        }
    }

    /**
     * 初始化列表
     */
    private fun initRecyclerView() {
        viewPagerLayoutManager.setOnViewPagerListener(object : OnViewPagerListener {
            override fun onPageSelected(position: Int, isBottom: Boolean) {
                // if (position == mCurPos) return
                startPlay(position)
            }

            override fun onPageRelease(isNext: Boolean, position: Int) {

            }

            override fun onInitComplete() {

            }
        })

        val recyclerView = findViewById<RecyclerView>(R.id.rv_discover)
        recyclerView.apply {
            layoutManager = viewPagerLayoutManager
            adapter = discoverAdapter
        }
        mRefreshLayout = findViewById(R.id.refreshLayout)
        mRefreshLayout!!.setRefreshHeader(WaterDropHeader(mActivity))
    }

    private fun initVideoView() {
        mVideoView = VideoView(mActivity)
        mVideoView!!.setLooping(true)
        mVideoView!!.setOnStateChangeListener(object : BaseVideoView.SimpleOnStateChangeListener() {
            override fun onPlayStateChanged(playState: Int) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    Utils.removeViewFormParent(mVideoView)
                    mLastPos = mCurPos
                    mCurPos = -1
                }
            }
        })
        mController = TikTokController(mActivity)
        mErrorView = ErrorView(activity)
        mController!!.addControlComponent(mErrorView)
        mController!!.addControlComponent(VideoVodControlView(mActivity))
        mController!!.setEnableOrientation(true)
        mVideoView!!.setVideoController(mController)
    }

    private fun observer() {

        // 切换tab
        observerRxBus(
            IndexVideoEvent::class.java
        ) { event ->
            if (event.type == 2) {
                releaseVideoView()
            } else {
                if (mLastPos == -1)
                    return@observerRxBus
                //恢复上次播放的位置
                startPlay(mLastPos)
            }
        }

        // 刷新列表
        observerRxBus(IndexLocalEvent::class.java) { event ->
            releaseVideoView()
            cityCode = event.cityCode
            lat = event.lat
            lng = event.lng
            findViewModel.getIndexDiscover(
                extraType,
                cityCode,
                lat,
                lng,
                mCurrentPage, PAGE_SIZE
            )
        }
        findViewModel.friendListSuccessEvent.observe(this) { list: List<IndexDataBean?>? ->
            if (!list.isNullOrEmpty()) {
                if (mCurrentPage == 1) {
                    discoverAdapter.removeEmptyView()
                    discoverAdapter.setList(list)
                } else {
                    discoverAdapter.addData(list)
                }
                discoverAdapter.loadMoreModule.loadMoreComplete()
            } else {
                if (mCurrentPage == 1) {
                    discoverAdapter.setList(ArrayList())
                    discoverAdapter.setEmptyView(emptyView)
                }
                discoverAdapter.loadMoreModule.loadMoreEnd()
            }
        }
        findViewModel.friendListFinallyEndEvent.observe(this) { flag: Boolean ->
            if (flag) {
                mRefreshLayout!!.finishRefresh()
            }
        }
    }

    /**
     * 列表刷新 加载 点击事件
     */
    private fun addListener() {
        mRefreshLayout!!.setOnRefreshListener(this)
        discoverAdapter.loadMoreModule.setOnLoadMoreListener {
            mCurrentPage++
            findViewModel.getIndexDiscover(
                extraType,
                BdLocationUtil.getInstance().cityCode.toString(),
                BdLocationUtil.getInstance().lat,
                BdLocationUtil.getInstance().lng,
                mCurrentPage, PAGE_SIZE
            )
        }
        discoverAdapter.addChildClickViewIds(
            R.id.img_add,
            R.id.riv_avatar,
            R.id.tv_like,
            R.id.tv_comment,
            R.id.tv_share,
            R.id.tv_detail,
            R.id.tv_position
        )
        discoverAdapter.setOnItemChildClickListener { adapter: BaseQuickAdapter<*, *>?, view: View, position: Int ->
            if (ViewUtil.isFastDoubleClick()) {
                return@setOnItemChildClickListener
            }
            val indexBean = discoverAdapter.getItem(position)
            if (view.id == R.id.img_add) {
                // 添加好友
                if (indexBean.followed) {
                    cancelFollowUser(indexBean.userId.toString(), position)
                } else {
                    followUser(indexBean.userId.toString(), position)
                }
            }
            if (view.id == R.id.riv_avatar) {
                // 用户详情
                RouterUser.PersonalDetailActivity(indexBean.userId.toString(), 1, "index")
            }
            if (view.id == R.id.tv_like) {
                // 点赞
                dynamicLike(indexBean.indexId, indexBean.moment.isLiked, position)
            }
            if (view.id == R.id.tv_comment) {
                // 评论
                val extras = Bundle()
                extras.putString("extra_dynamic_id", indexBean.indexId)
                DynamicCommentDialog.showDialog(
                    mActivity,
                    com.yzt.dynamicmodule.dialog.DynamicCommentDialog::class.java,
                    extras
                )
            }
            if (view.id == R.id.tv_share) {
                // 分享
                val share = BaseDialog.showDialog(
                    mActivity, IndexShareDialog::class.java
                ) as IndexShareDialog
                share.setListener { ToastUtil.showMessage("分享") }
            }
            if (view.id == R.id.tv_detail) {
                // 详情
                if (indexBean.activity != null) {
                    RouterDynamic.GameDetailActivity(indexBean.indexId)
                } else {
                    val extras = Bundle()
                    extras.putString("extra_dynamic_id", indexBean.indexId)
                    DynamicDetailDialog.showDialog(
                        mActivity,
                        com.yzt.dynamicmodule.dialog.DynamicDetailDialog::class.java,
                        extras
                    )
                }
            }
            if (view.id == R.id.tv_position) {
                // 位置
                val dialog = BaseDialog.showDialog(
                    mActivity, AddressGoOnDialog::class.java
                ) as AddressGoOnDialog
                dialog.setListener {
                    val stringBuffer = StringBuffer("baidumap://map/navi?location=")
                        .append("28.680242").append(",").append("115.980541").append("&type=TIME");
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(stringBuffer.toString()));
                    intent.setPackage("com.baidu.BaiduMap");
                    startActivity(intent);
                }
            }
        }
    }

    override fun netWorkRequest() {

    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mCurrentPage = 1
        findViewModel.getIndexDiscover(
            extraType,
            BdLocationUtil.getInstance().cityCode.toString(),
            BdLocationUtil.getInstance().lat,
            BdLocationUtil.getInstance().lng,
            mCurrentPage, PAGE_SIZE
        )
    }

    /**
     * 关注用户
     */
    private fun followUser(mUserId: String, position: Int) {
        val mFollowRequest = FollowUserStatusRequest()
        val list: MutableList<String> = ArrayList()
        list.add(mUserId)
        mFollowRequest.uidRels = list
        mFollowRequest.status = 1
        BizLayer.getInstance().accountModule.postFollowOrUnfollowUser(mFollowRequest,
            object : AresSubscriber<HttpResponse<*>>() {
                override fun onSuccess(response: HttpResponse<*>) {
                    ToastUtil.showMessage("关注成功！")
                    discoverAdapter.data[position].isFollowed = true
                    discoverAdapter.notifyItemChanged(position)
                }
            })
    }

    /**
     * 关注用户
     */
    private fun cancelFollowUser(mUserId: String, position: Int) {
        val mFollowRequest = FollowUserStatusRequest()
        val list: MutableList<String> = ArrayList()
        list.add(mUserId)
        mFollowRequest.uidRels = list
        mFollowRequest.status = 0
        BizLayer.getInstance().accountModule.postFollowOrUnfollowUser(mFollowRequest,
            object : AresSubscriber<HttpResponse<*>>() {
                override fun onSuccess(response: HttpResponse<*>) {
                    ToastUtil.showMessage("取消关注！")
                    discoverAdapter.data[position].isFollowed = false
                    discoverAdapter.notifyItemChanged(position)
                }
            })
    }

    /**
     * 动态点赞
     */
    private fun dynamicLike(dynamicId: String, status: Boolean, position: Int) {
        if (status) {
            BizLayer.getInstance().dynamicModule.dynamicUnLike(dynamicId,
                object : AresSubscriber<HttpResponse<*>>() {
                    override fun onSuccess(response: HttpResponse<*>) {
                        var likeCount = discoverAdapter.data[position].moment.likeNum
                        likeCount--
                        discoverAdapter.data[position].moment.likeNum = likeCount
                        discoverAdapter.data[position].moment.isLiked = false
                        discoverAdapter.notifyItemChanged(position)
                    }
                })
        } else {
            BizLayer.getInstance().dynamicModule.dynamicLike(dynamicId,
                object : AresSubscriber<HttpResponse<*>>() {
                    override fun onSuccess(response: HttpResponse<*>) {
                        var likeCount = discoverAdapter.data[position].moment.likeNum
                        likeCount++
                        discoverAdapter.data[position].moment.likeNum = likeCount
                        discoverAdapter.data[position].moment.isLiked = true
                        discoverAdapter.notifyItemChanged(position)
                    }
                })
        }
    }

    /**
     * 播放视频
     */
    private fun startPlay(position: Int) {
        if (mCurPos == position) {
            return
        }
        if (mCurPos != -1) {
            releaseVideoView()
        }
        if (discoverAdapter.data.size <= position) {
            return
        }
        val videoBean: IndexDataBean = discoverAdapter.data[position]

        if (videoBean.activity == null && videoBean.moment.contentType != 2) {
            return
        }
        val videoPath =
            if (videoBean.activity != null) videoBean.activity.activityFileUrl else videoBean.moment.momentUrls[0]
        // 视频缓存
        val proxyUrl = BaseApplication.getVideoCacheProxy(mActivity).getProxyUrl(videoPath)
        mVideoView!!.setUrl(proxyUrl)
        if (discoverAdapter.getViewByPosition(position, R.id.video_view) == null) {
            return
        }
        val mPrepareView = discoverAdapter.getViewByPosition(
            position, R.id.video_view
        ) as VideoPrepareView
        if (discoverAdapter.getViewByPosition(
                position, R.id.video_container
            ) == null
        ) {
            return
        }
        val mPlayerContainer = discoverAdapter.getViewByPosition(
            position, R.id.video_container
        ) as FrameLayout
        mController!!.addControlComponent(mPrepareView, true)
        Utils.removeViewFormParent(mVideoView)
        mPlayerContainer.addView(mVideoView, 0)
        VideoViewManager.instance().add(mVideoView, "list")
        mVideoView!!.start()
        mCurPos = position
    }

    override fun onPause() {
        super.onPause()
        releaseVideoView()
    }

    private fun releaseVideoView() {
        mVideoView?.let {
            mVideoView!!.release()
        }
        if (mActivity.requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            mActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        mCurPos = -1
    }

    override fun onResume() {
        super.onResume()
        if (mLastPos == -1) return
        //恢复上次播放的位置
        startPlay(mLastPos)
    }
}